<template>
  <div>
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">{{ isEditMode ? "编辑项目" : "新建项目" }}</h1>
        <p class="page-description">
          {{ isEditMode ? "编辑现有项目信息" : "创建一个新的项目展示" }}
        </p>
      </div>
      <div class="header-right">
        <el-space>
          <el-button @click="$router.back()">
            <Icon name="fa:arrow-left" />
            返回
          </el-button>
          <el-button @click="handleSaveDraft" :loading="saving">
            <Icon name="fa:save" />
            {{ isEditMode ? "保存修改" : "保存草稿" }}
          </el-button>
          <el-button
            type="primary"
            @click="handlePublish"
            :loading="publishing"
          >
            <Icon name="fa:send" />
            {{ isEditMode ? "更新项目" : "发布项目" }}
          </el-button>
        </el-space>
      </div>
    </div>

    <!-- 项目编辑表单 -->
    <el-row :gutter="24">
      <!-- 主要内容区域 -->
      <el-col :xs="24" :lg="18">
        <el-card class="editor-card">
          <el-form :model="form" :rules="rules" label-position="top">
            <!-- 项目标题 -->
            <el-form-item label="项目标题" prop="title" required>
              <el-input
                v-model="form.title"
                placeholder="请输入项目标题"
                size="large"
              />
            </el-form-item>

            <!-- 项目描述 -->
            <el-form-item label="项目描述" prop="description" required>
              <el-input
                v-model="form.description"
                type="textarea"
                placeholder="请输入项目描述，用于项目列表展示"
                :rows="3"
                show-word-limit
                :maxlength="200"
              />
            </el-form-item>

            <!-- 项目内容 -->
            <el-form-item label="项目内容" prop="content" required>
              <div class="editor-container">
                <MdEditor
                  v-model="form.content"
                  :theme="editorTheme"
                  placeholder="请输入项目内容，支持 Markdown 语法"
                  style="height: calc(100vh - 660px)"
                  :toolbars="[
                    'bold',
                    'underline',
                    'italic',
                    '-',
                    'title',
                    'strikeThrough',
                    'sub',
                    'sup',
                    'quote',
                    'unorderedList',
                    'orderedList',
                    '-',
                    'codeRow',
                    'code',
                    'link',
                    'image',
                    'table',
                    'mermaid',
                    'katex',
                    '-',
                    'revoke',
                    'next',
                    'save',
                    '=',
                    'pageFullscreen',
                    'fullscreen',
                    'preview',
                    'htmlPreview',
                    'catalog',
                  ]"
                />
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 侧边栏 -->
      <el-col :xs="24" :lg="6">
        <!-- 项目信息 -->
        <el-card title="项目信息" class="sidebar-card">
          <el-form-item label="项目分类">
            <el-select
              v-model="form.category"
              placeholder="请选择项目分类"
              style="width: 100%"
            >
              <el-option
                v-for="category in categories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="项目状态">
            <el-select v-model="form.status" style="width: 100%">
              <el-option value="draft">草稿</el-option>
              <el-option value="inProgress">进行中</el-option>
              <el-option value="published">已发布</el-option>
              <el-option value="completed">已完成</el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="岗位角色">
            <el-input
              v-model="form.role"
              placeholder="如：前端工程师、全栈开发等"
            />
          </el-form-item>
        </el-card>

        <!-- 链接信息 -->
        <el-card title="链接信息" class="sidebar-card">
          <el-form-item label="GitHub" label-width="80px">
            <el-input
              v-model="form.github"
              placeholder="https://github.com/..."
            />
          </el-form-item>

          <el-form-item label="演示链接" label-width="80px">
            <el-input
              v-model="form.demo"
              placeholder="https://demo.example.com"
            />
          </el-form-item>
        </el-card>

        <!-- 技术栈 -->
        <el-card title="技术栈" class="sidebar-card">
          <el-form-item label="技术标签">
            <el-select
              v-model="form.technologies"
              multiple
              placeholder="选择或输入技术标签"
              style="width: 100%"
              filterable
              allow-create
              default-first-option
            >
              <el-option
                v-for="tech in commonTechnologies"
                :key="tech"
                :value="tech"
                :label="tech"
              />
            </el-select>
          </el-form-item>
        </el-card>

        <!-- 项目图片 -->
        <el-card title="项目图片" class="sidebar-card">
          <div class="cover-image-section">
            <div v-if="form.image_url" class="cover-preview">
              <img :src="form.image_url" alt="项目图片" />
              <div class="cover-actions">
                <el-button size="small" type="danger" @click="removeCoverImage">
                  <Icon name="fa:trash" />
                  移除
                </el-button>
              </div>
            </div>
            <div v-else class="cover-upload">
              <el-upload
                :show-file-list="false"
                :before-upload="handleCoverUpload"
                accept="image/*"
              >
                <el-button>
                  <Icon name="fa:upload" />
                  上传项目图片
                </el-button>
              </el-upload>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
// 导入 md-editor-v3
import { MdEditor } from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import type { ApiResponse } from "~/types/api";

// 获取当前颜色模式
const colorMode = useColorMode();

// 根据主题动态设置编辑器主题
const editorTheme = computed(() => {
  return colorMode.value === 'dark' ? 'dark' : 'light';
});

// 路由参数
const route = useRoute();

const projectId = route.params.id as string;
// 如果是 "create" 字符串，表示创建模式；否则是编辑模式
const isEditMode = computed(() => projectId !== "0");

// 响应式数据
const saving = ref(false);
const publishing = ref(false);
const loading = ref(false);

// 分类数据
interface Category {
  id: string;
  name: string;
}

const categories = ref<Category[]>([]);

// 表单数据
const form = ref({
  title: "",
  description: "",
  content: "",
  category: "",
  status: "draft",
  github: "",
  demo: "",
  technologies: [],
  image: 0,
  image_url: "",
  role: "",
});

// 表单验证规则
const rules = {
  title: [
    { required: true, message: "请输入项目标题", trigger: "blur" },
    {
      min: 1,
      max: 100,
      message: "标题长度应在1-100个字符之间",
      trigger: "blur",
    },
  ],
  description: [{ required: true, message: "请输入项目描述", trigger: "blur" }],
  content: [{ required: true, message: "请输入项目内容", trigger: "blur" }],
  // 封面图片
  image: [{ required: true, message: "请上传项目封面图片", trigger: "blur" }],
};

// 常用技术栈
const commonTechnologies = [
  "React",
  "Vue.js",
  "Angular",
  "Node.js",
  "TypeScript",
  "JavaScript",
  "Python",
  "Java",
  "Go",
  "Rust",
  "PHP",
  "Ruby",
  "MongoDB",
  "MySQL",
  "PostgreSQL",
  "Redis",
  "Docker",
  "Kubernetes",
  "AWS",
  "Azure",
  "GCP",
  "Tailwind CSS",
  "Bootstrap",
  "Sass",
];

// 方法

const handleCoverUpload = async (file: File) => {
  try {
    // 创建FormData对象
    const formData = new FormData();
    formData.append("file", file);
    formData.append("category", "projects");

    // 调用上传接口
    const response = await $fetch("/api/upload", {
      method: "POST",
      body: formData,
    });

    if (response.success) {
      // 设置图片URL
      form.value.image = response.data.id || 0;
      form.value.image_url = response.data.url || "";
      ElMessage.success("图片上传成功");
    } else {
      ElMessage.error("上传失败");
    }
  } catch (error: any) {
    console.error("上传失败:", error);
    ElMessage.error(error.data?.message || "上传失败");
  }

  return false; // 阻止默认上传
};

const removeCoverImage = () => {
  form.value.image = 0;
  form.value.image_url = "";
};

const handleSaveDraft = async () => {
  saving.value = true;
  try {
    // 表单验证
    if (!form.value.title || !form.value.description) {
      ElMessage.error("请填写标题和描述");
      return;
    }

    // 准备提交数据
    const submitData = {
      title: form.value.title,
      description: form.value.description,
      content: form.value.content || "",
      category: form.value.category,
      technologies: form.value.technologies,
      status: "draft",
      featured: false,
      coverImage: form.value.image,
      demoUrl: form.value.demo,
      githubUrl: form.value.github,
      role: form.value.role,
    };

    let response;
    if (isEditMode.value) {
      // 编辑模式：更新项目
      response = await $fetch<ApiResponse<{ id: string }>>(
        `/api/admin/projects/${projectId}`,
        {
          method: "PUT",
          body: submitData,
        }
      );
    } else {
      // 创建模式：新建项目
      response = await $fetch<ApiResponse<{ id: string }>>(
        "/api/admin/projects",
        {
          method: "POST",
          body: submitData,
        }
      );
    }

    if (response.success) {
      ElMessage.success(
        isEditMode.value ? "项目修改保存成功" : "项目草稿保存成功"
      );
      navigateTo("/admin/projects");
    } else {
      ElMessage.error(response.message || "保存失败");
    }
  } catch (error: any) {
    console.error("保存失败:", error);
    ElMessage.error(
      error.data?.message ||
        (isEditMode.value ? "保存修改失败" : "保存草稿失败")
    );
  } finally {
    saving.value = false;
  }
};

const handlePublish = async () => {
  publishing.value = true;
  try {
    // 表单验证
    if (!form.value.title || !form.value.description) {
      ElMessage.error("请填写标题和描述");
      return;
    }

    // 准备提交数据
    const submitData = {
      title: form.value.title,
      description: form.value.description,
      content: form.value.content || "",
      category: form.value.category,
      technologies: form.value.technologies,
      status: form.value.status,
      featured: false,
      coverImage: form.value.image,
      demoUrl: form.value.demo,
      githubUrl: form.value.github,
      role: form.value.role,
    };

    let response;
    if (isEditMode.value) {
      // 编辑模式：更新项目
      response = await $fetch<ApiResponse<{ id: string }>>(
        `/api/admin/projects/${projectId}`,
        {
          method: "PUT",
          body: submitData,
        }
      );
    } else {
      // 创建模式：新建项目
      response = await $fetch<ApiResponse<{ id: string }>>(
        "/api/admin/projects",
        {
          method: "POST",
          body: submitData,
        }
      );
    }

    if (response.success) {
      ElMessage.success(isEditMode.value ? "项目更新成功" : "项目发布成功");
      navigateTo("/admin/projects");
    } else {
      ElMessage.error(
        response.message || (isEditMode.value ? "更新项目失败" : "发布项目失败")
      );
    }
  } catch (error: any) {
    console.error("操作失败:", error);
    ElMessage.error(
      error.data?.message ||
        (isEditMode.value ? "更新项目失败" : "发布项目失败")
    );
  } finally {
    publishing.value = false;
  }
};

// 获取分类数据
const loadCategories = async () => {
  try {
    const response = await $fetch<ApiResponse<any[]>>("/api/categories");
    if (response.data) {
      categories.value = response.data;
    }
  } catch (error: any) {
    console.error("获取分类数据失败:", error);
    ElMessage.error("获取分类数据失败");
  }
};

// 加载项目数据（编辑模式）
const loadProjectData = async () => {
  if (!isEditMode.value) return;

  loading.value = true;
  try {
    const response = await $fetch<ApiResponse<any>>(
      `/api/admin/projects/${projectId}`
    );
    if (response.data) {
      const project = response.data;
      // 填充表单数据 - 只填充数据库中存在的字段
      form.value = {
        title: project.title || "",
        description: project.description || "",
        content: project.content || "",
        category: project.category,
        status: project.status || "draft",
        github: project.github_url || "",
        demo: project.demo_url || "",
        technologies: project.technologies || [],
        image: project.cover_image_id || "",
        image_url: project.cover_image_url || "",
        role: project.role || "",
      };
    }
  } catch (error: any) {
    console.error("加载项目数据失败:", error);
    ElMessage.error(error.data?.message || "加载项目数据失败");
  } finally {
    loading.value = false;
  }
};

// 页面元数据
useHead({
  title: computed(
    () => `${isEditMode.value ? "编辑" : "新建"}项目 - 项目管理系统`
  ),
});

// 初始化
onMounted(async () => {
  await loadCategories();
  if (isEditMode.value) {
    await loadProjectData();
  }
});
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 4px 0;
  color: #1a1a1a;
}

.page-description {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.editor-card {
  border-radius: 12px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.sidebar-card {
  margin-bottom: 16px;
  border-radius: 12px;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.editor-container {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
}

.cover-image-section {
  text-align: center;
  padding: 16px;
}

.cover-preview {
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.cover-preview img {
  width: 100%;
  max-height: 240px;
  object-fit: cover;
  border-radius: 8px;
}

.cover-actions {
  margin-top: 12px;
  display: flex;
  gap: 8px;
  justify-content: center;
}

.cover-upload {
  padding: 32px 24px;
  border: 2px dashed #d9d9d9;
  border-radius: 12px;
  background: #fafafa;
  transition: all 0.3s ease;
  cursor: pointer;
}

.cover-upload:hover {
  border-color: #409eff;
  background: #f0f7ff;
}

.cover-upload:active {
  transform: scale(0.98);
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 8px;
}

:deep(.el-input) {
  border-radius: 8px;
}

:deep(.el-textarea__inner) {
  border-radius: 8px;
  resize: vertical;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-card__header) {
  border-bottom: 1px solid #f0f0f0;
  padding: 20px 24px;
  font-weight: 600;
  color: #1a1a1a;
}

:deep(.el-card__body) {
  padding: 24px;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .create-project-page {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
    padding: 20px;
  }

  .header-right {
    align-self: stretch;
  }

  :deep(.el-row) {
    margin: 0 -8px;
  }

  :deep(.el-col) {
    padding: 0 8px;
  }
}

/* 动画效果 */
.page-header,
.editor-card,
.sidebar-card {
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 暗色主题适配 */

.dark .page-header {
  background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}

.dark .page-title {
  color: #f8fafc;
  font-weight: 700;
  background: linear-gradient(135deg, #f8fafc, #cbd5e1);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.dark .page-description {
  color: #94a3b8;
}

.dark .editor-card,
.dark .sidebar-card {
  background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}

.dark .cover-preview {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
}

.dark .cover-upload {
  border: 2px dashed rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.05);
}

.dark .cover-upload:hover {
  border-color: #3b82f6;
  background: rgba(59, 130, 246, 0.1);
}

/* 表单样式暗色主题 */
.dark :deep(.el-form-item__label) {
  color: #f8fafc;
}

.dark :deep(.el-input__inner) {
  background: #1e293b;
  border-color: rgba(255, 255, 255, 0.2);
  color: #f8fafc;
}

.dark :deep(.el-input__inner:focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
}

.dark :deep(.el-input__inner::placeholder) {
  color: #64748b;
}

.dark :deep(.el-input__inner:hover) {
  border-color: rgba(255, 255, 255, 0.3);
}

.dark :deep(.el-textarea__inner) {
  background: #1e293b;
  border-color: rgba(255, 255, 255, 0.2);
  color: #f8fafc;
}

.dark :deep(.el-textarea__inner:focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
}

.dark :deep(.el-textarea__inner::placeholder) {
  color: #64748b;
}

.dark :deep(.el-select) {
  width: 100%;
}

.dark :deep(.el-select .el-input__inner) {
  background: #1e293b;
  border-color: rgba(255, 255, 255, 0.2);
  color: #f8fafc;
}

.dark :deep(.el-select .el-input.is-focus .el-input__inner) {
  border-color: #3b82f6;
}

.dark :deep(.el-card__header) {
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  color: #f8fafc;
  background: rgba(255, 255, 255, 0.02);
}

.dark :deep(.el-card__body) {
  background: transparent;
}

/* 按钮样式暗色主题 */
.dark :deep(.el-button) {
  border-color: rgba(255, 255, 255, 0.2);
}

.dark :deep(.el-button--default) {
  background: rgba(255, 255, 255, 0.05);
  color: #f8fafc;
}

.dark :deep(.el-button--default:hover) {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.3);
}

.dark :deep(.el-button--primary) {
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  border: none;
}

.dark :deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
}

.dark :deep(.el-button--danger) {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  border: none;
}

.dark :deep(.el-button--danger:hover) {
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
}

/* Select 下拉框暗色主题 */
.dark :deep(.el-select-dropdown) {
  background: #1e293b;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.dark :deep(.el-select-dropdown__item) {
  color: #f8fafc;
}

.dark :deep(.el-select-dropdown__item:hover) {
  background: rgba(59, 130, 246, 0.1);
}

.dark :deep(.el-select-dropdown__item.selected) {
  color: #3b82f6;
  background: rgba(59, 130, 246, 0.1);
}

/* 上传组件暗色主题 */
.dark :deep(.el-upload) {
  background: #1e293b;
  border-color: rgba(255, 255, 255, 0.2);
}

.dark :deep(.el-upload-dragger) {
  background: #1e293b;
  border-color: rgba(255, 255, 255, 0.2);
}

.dark :deep(.el-upload-dragger:hover) {
  border-color: #3b82f6;
  background: rgba(59, 130, 246, 0.05);
}

/* 滚动条暗色主题 */
.dark ::-webkit-scrollbar-track {
  background: #334155;
}

.dark ::-webkit-scrollbar-thumb {
  background: #64748b;
}

.dark ::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style>
